package com.emm.yixun.website.controller.marketing;

//框架包
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.emm.yixun.common.model.BusinessAbnorma;
import com.emm.yixun.common.model.NeedReceiveRefund;
import com.emm.yixun.common.model.NeedReceiveRefundInfo;
import com.emm.yixun.common.model.PayDeposit;
import com.emm.yixun.common.model.ReserveArea;
import com.emm.yixun.common.model.Signed;
import com.emm.yixun.common.model.SignedInfo;
import com.emm.yixun.common.model.SubscribeInfo;
import com.emm.yixun.common.model.User;
import com.emm.yixun.common.model.dto.BusinessAbnormaDto;
import com.emm.yixun.common.model.dto.HaveReceiveRefundDto;
import com.emm.yixun.common.model.dto.NeedReceiveRefundDto;
import com.emm.yixun.common.model.dto.NeedReceiveRefundInfoDto;
import com.emm.yixun.common.model.dto.NeedReceiveRefundView;
import com.emm.yixun.common.model.enums.AuditStatusEnum;
import com.emm.yixun.common.model.enums.BusinessAbnormaEnum;
import com.emm.yixun.common.model.enums.BusinessTypeEnum;
import com.emm.yixun.common.model.enums.DocTypeEnum;
import com.emm.yixun.common.page.Page;
import com.emm.yixun.common.page.PageUtil;
import com.emm.yixun.common.response.Response;
import com.emm.yixun.common.response.ResponseList;
import com.emm.yixun.common.utils.BeanUtil;
import com.emm.yixun.common.utils.DateStyle;
import com.emm.yixun.common.utils.DateUtils;
import com.emm.yixun.customer.service.PayDepositServiceFacade;
import com.emm.yixun.customer.service.SignedServiceFacade;
import com.emm.yixun.customer.service.SubscribeServiceFacade;
import com.emm.yixun.marketing.service.BusinessAbnormaServiceFacade;
import com.emm.yixun.marketing.service.HaveReceiveRefundServiceFacade;
import com.emm.yixun.marketing.service.NeedReceiveRefundServiceFacade;
import com.emm.yixun.marketing.service.ReserveAreaServiceFacade;
import com.emm.yixun.system.service.MerchantServiceFacade;
import com.emm.yixun.system.service.UserServiceFacade;
import com.emm.yixun.website.common.ajax.AjaxRes;
import com.emm.yixun.website.common.utils.base.Const;
import com.emm.yixun.website.common.utils.security.ShiroUtil;
import com.emm.yixun.website.controller.base.BaseController;
import com.emm.yixun.website.service.marketing.NeedReceicerefundExportService;
import com.emm.yixun.website.utils.ExcelUtil;
//common
//website
//变化的引用
import com.emm.yixun.website.vo.common.ExtResultVo;

@Controller
@RequestMapping("/marketing/needReceiveRefund/")
public class NeedReceiveRefundController extends BaseController<NeedReceiveRefund> {

	@Autowired
	private NeedReceiveRefundServiceFacade needReceiveRefundServiceFacade;
	@Autowired
	private HaveReceiveRefundServiceFacade haveReceiveRefundServiceFacade;
	@Autowired
	private SignedServiceFacade signedServiceFacade;
	@Autowired
	private ReserveAreaServiceFacade reserveAreaServiceFacade;
	@Autowired
	private PayDepositServiceFacade payDepositServiceFacade;
	@Autowired
	private SubscribeServiceFacade subscribeServiceFacade;
	@Autowired
	private UserServiceFacade userServiceFacade;
	@Autowired
	private MerchantServiceFacade merchantServiceFacade;
	@Autowired
	private BusinessAbnormaServiceFacade businessAbnormaServiceFacade;
	@Autowired
	private NeedReceicerefundExportService needReceicerefundExportService;

	@RequestMapping(value = "index")
	public String index(ModelMap map) {
		if (doSecurityIntercept(Const.RESOURCES_TYPE_MENU)) {

			// 认筹开关,默认未关闭
			User user = ShiroUtil.getCurrentUser();
			boolean payDepositOff = false;
			Response<Boolean> response = merchantServiceFacade.merPayDepositOff(user.getMerchantId());
			if (response.isSuccess()) {
				payDepositOff = response.getEntity();
			}
			// 查询菜单按钮权限
			map.put("permitBtn", getPermissionBtnArray());
			map.put("payDepositOff", payDepositOff);
			return "/marketing/needReceiveRefund/list";
		}
		return Const.NO_AUTHORIZED_URL;
	}

	// 新增返回实体对象
	@RequestMapping(value = "add", method = RequestMethod.POST)
	@ResponseBody
	public AjaxRes add(NeedReceiveRefundDto dto) {
		AjaxRes ar = getAjaxRes();

		/*
		 * 1.判断权限2.调用新增接口3.返回信息
		 */
		if (ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON, "marketing:needReceiveRefund:add"))) {
			try {
				User user = ShiroUtil.getCurrentUser();
				dto.setMerchantId(user.getMerchantId());
				dto.setCreateUserId(user.getId());
				dto.setDelFlag("0");
				dto.setUpdateUserId(user.getId());
				dto.setUpdateTime(new Date());
				Response<NeedReceiveRefundDto> response = needReceiveRefundServiceFacade.save(dto);
				if (response.isSuccess()) {
					ar.setSucceedMsg(Const.SAVE_SUCCEED);
				} else {
					ar.setFailMsg(Const.SAVE_FAIL);
				}
			} catch (Exception e) {
				logger.error(e.toString(), e);
				ar.setFailMsg(Const.SAVE_FAIL);
			}
		}
		return ar;
	}

	// 查看
	@RequestMapping(value = "view", method = RequestMethod.POST)
	@ResponseBody
	public AjaxRes view(Long id) {
		AjaxRes ar = getAjaxRes();
		/*
		 * 1.判断权限2.调用查看接口3.返回信息
		 */
		if (ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON, "marketing:needReceiveRefund:view"))) {
			try {
				Response<NeedReceiveRefund> response = needReceiveRefundServiceFacade.findById(id);
				if (response.isSuccess()) {
					ar.setSucceed(response.getEntity());
				} else {
					ar.setFailMsg(Const.DATA_FAIL);
				}
			} catch (Exception e) {
				logger.error(e.toString(), e);
				ar.setFailMsg(Const.DATA_FAIL);
			}
		}
		return ar;
	}

	// 退款
	@RequestMapping(value = "refund_view")
	public String refund_view(Long id, Model model) {
		/*
		 * 1.判断权限2.调用查看接口3.返回信息
		 */
		if (doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON, "fin:haveReceive:refund")) {
			try {
				User user = ShiroUtil.getCurrentUser();

				Response<NeedReceiveRefundInfo> response = needReceiveRefundServiceFacade.findInfoById(id);
				if (response.isSuccess()) {
					NeedReceiveRefundInfo info = response.getEntity();
					if (info.getRelationId() != null) {
						if (info.getBusinessType().equals(BusinessTypeEnum.DEPOSIT.getNo())) {
							// 认筹
							Response<PayDeposit> resp = payDepositServiceFacade.findById(info.getRelationId());
							if (resp.isSuccess() && resp.getEntity() != null) {
								info.setRelation("认筹");
								info.setRelationCode(resp.getEntity().getDepositCode());
							}
						} else if (info.getBusinessType().equals(BusinessTypeEnum.SUBSCRIBE.getNo())) {
							// 认购
							Response<SubscribeInfo> resp = subscribeServiceFacade.findByIdInfo(info.getRelationId());
							if (resp.isSuccess() && resp.getEntity() != null) {
								info.setRelation("认购");
								info.setRelationCode(resp.getEntity().getSubscribeCode());
								if (resp.getEntity() != null) {
									info.setAgent_name(resp.getEntity().getUserName());
								}
							}
						} else if (info.getBusinessType().equals(BusinessTypeEnum.SIGNED.getNo())) {
							// 查询签约信息
							Response<SignedInfo> resp = signedServiceFacade.findByIdInfo(info.getRelationId());
							if (resp.isSuccess() && resp.getEntity() != null) {
								info.setRelation("签约");
								info.setRelationCode(resp.getEntity().getSignCode());
								info.setCalculatArea(resp.getEntity().getCalculateArea().toString());
								info.setPrice(resp.getEntity().getSignPrice());
								info.setTotalPrice(resp.getEntity().getSignAmount());
								info.setRelationDate(resp.getEntity().getDidTime());
								if (resp.getEntity() != null) {
									info.setAgent_name(resp.getEntity().getUserName());
								}
							}
						} else if (info.getBusinessType().equals(BusinessTypeEnum.AREA.getNo())) {
							// 面积补差
							Response<ReserveArea> res = reserveAreaServiceFacade.findById(info.getRelationId());
							if (res.isSuccess() && res.getEntity() != null) {
								info.setRelation("面积补差");
								info.setRelationCode(res.getEntity().getId() + "");
								// 签约信息
								Response<Signed> resp = signedServiceFacade.findById(res.getEntity().getSignedId());
								if (resp.isSuccess() && resp.getEntity() != null) {
									info.setCalculatArea(resp.getEntity().getCalculateArea().toString());
									info.setPrice(resp.getEntity().getSignPrice());
									info.setTotalPrice(resp.getEntity().getSignAmount());
									info.setRelationDate(resp.getEntity().getDidTime());
									if (resp.getEntity().getAgentId() != null) {
										Response<User> resUser = userServiceFacade.findById(resp.getEntity()
												.getAgentId());
										info.setAgent_name(resUser.getEntity().getUserName());
									}
								}
							}
						}
					}
					HaveReceiveRefundDto queryHaveReceiveRefundDto=new HaveReceiveRefundDto();
					queryHaveReceiveRefundDto.setReceivablesId(id);
					queryHaveReceiveRefundDto.setTransferStatus("0");
					queryHaveReceiveRefundDto.setDocType("1");
					Double havaReceiveAmount=haveReceiveRefundServiceFacade.haveReceiveAmount(queryHaveReceiveRefundDto);
					if(null==havaReceiveAmount)havaReceiveAmount=Double.valueOf("0");
					info.setRealAmount(info.getTotalReceivablesAmount().subtract(new BigDecimal(havaReceiveAmount)));
					/*Response<BigDecimal> hraResponse = haveReceiveRefundServiceFacade.findHaveAmount(id);
					if (hraResponse.isSuccess()) {
						info.setRealAmount(info.getTotalReceivablesAmount().subtract(hraResponse.getEntity()));
					}*/
					model.addAttribute("userId", user.getId());
					model.addAttribute("userName", user.getUserName());
					model.addAttribute("model", info);
					model.addAttribute("needOrHave", "need");
					model.addAttribute("isDtk", true);
				}
			} catch (Exception e) {
				logger.error(e.toString(), e);
			}
		}
		return "/marketing/haveReceiveRefund/refund";
	}

	// 修改
	@RequestMapping(value = "edit", method = RequestMethod.POST)
	@ResponseBody
	public AjaxRes edit(NeedReceiveRefundDto dto) {
		AjaxRes ar = getAjaxRes();
		/*
		 * 1.判断权限2.调用修改接口3.返回信息
		 */
		if (ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON, "marketing:needReceiveRefund:edit"))) {
			try {
				Response<Integer> response = needReceiveRefundServiceFacade.updateByPrimaryKey(dto, true);
				if (response.isSuccess()) {
					ar.setSucceedMsg(Const.UPDATE_SUCCEED);
				} else {
					ar.setFailMsg(Const.UPDATE_FAIL);
				}
			} catch (Exception e) {
				logger.error(e.toString(), e);
				ar.setFailMsg(Const.UPDATE_FAIL);
			}
		}
		return ar;
	}

	// 删除
	@RequestMapping(value = "delete", method = RequestMethod.POST)
	@ResponseBody
	public AjaxRes delete(Long id) {
		AjaxRes ar = getAjaxRes();
		/*
		 * 1.判断权限2.调用查看接口3.返回信息
		 */
		if (ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON, "marketing:needReceiveRefund:delete"))) {
			try {
				Response<Integer> response = needReceiveRefundServiceFacade.deleteByPrimaryKey(id);
				if (response.isSuccess()) {
					ar.setSucceedMsg(Const.DEL_SUCCEED);
				} else {
					ar.setFailMsg(Const.DEL_FAIL);
				}
			} catch (Exception e) {
				logger.error(e.toString(), e);
				ar.setFailMsg(Const.DEL_FAIL);
			}
		}
		return ar;
	}
	/**
	 * 
	 * needReceicerefundExport:(待收款明细). <br/>
	 * @author Administrator
	 * @param request
	 * @param dto
	 * @param response
	 * @since JDK 1.6
	 */
	@RequestMapping(value = "needReceicerefundExport")
	public void needReceicerefundExport(HttpServletRequest request, String json,HttpServletResponse response){
		try {
			AjaxRes ar = getAjaxRes();
			if (ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON,"fin:needReceive:list"))) {
				String[] name = null;
				List<String[]> headerList = new ArrayList<String[]>(); 
				List<List<Map<String, String>>> list = new ArrayList<List<Map<String, String>>>(); //数据集合
				String[] header = null;
				
				String jsonStr=URLDecoder.decode(json,"utf-8");
				NeedReceiveRefundInfoDto dto = JSONObject.parseObject(jsonStr, NeedReceiveRefundInfoDto.class);
				if(dto.getDocType().equals(DocTypeEnum.COLLECTION.getNo())){
					name = new String[]{"待收款明细"};
					header = new String[]{
							"客户名称","房号","签约面积(㎡)","签约单价(元)","签约金额(元)","房款类型","应收金额(元)","应收日期","已收金额(元)","未收金额(元)"
					};
				}else{
					name = new String[]{"待退款明细"};
					header = new String[]{
							"客户名称","房号","签约面积(㎡)","签约单价(元)","签约金额(元)","退款类型","可退金额(元)","经办日期","经办人","备注"
					};
				}
				headerList.add(header);
				dto = setQueryNeedReceiveRefund(dto);
				dto.setIsExport("1");
				Page<NeedReceiveRefundInfo> responseList = needReceiveRefundServiceFacade.findPageByDtoInfo(dto,
						PageUtil.begin(0, 10), 10);
				List<Map<String, String>> listMap = needReceicerefundExportService.returnFieldNeedReceiveRefund(responseList.getRows(), header,dto.getDocType());
				list.add(listMap);
				ExcelUtil.exportExcel(list, headerList, name, response);
			}
		} catch (Exception e) {
			logger.error("needReceicerefundExport error: ", e);
		}
	}

	// 分页查询
	@RequestMapping(value = "list")
	@ResponseBody
	public Page<NeedReceiveRefundInfo> list(HttpServletRequest request, NeedReceiveRefundInfoDto dto, Integer page,
			Integer limit) {
		/*
		 * 1.判断权限2.调用分页查询接口3.返回信息
		 */
		if (doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON, "fin:needReceive:list")) {
			try {
				dto.setYsDateStart(request.getParameter("ysDateStart"));
				dto.setYsDateEnd(request.getParameter("ysDateEnd"));
				dto = setQueryNeedReceiveRefund(dto);
				Page<NeedReceiveRefundInfo> response = needReceiveRefundServiceFacade.findPageByDtoInfo(dto,
						PageUtil.begin(page, limit), limit);
				if (response.getSuccess()) {
					if (null == response.getRows()) {
						response.setRows(new ArrayList<NeedReceiveRefundInfo>());
					}
					response.setPageNumber(page);
					return response;
				} else {
				}
			} catch (Exception e) {
				logger.error(e.toString(), e);
			}
		}
		return new Page<NeedReceiveRefundInfo>();
	}
	/**
	 * 
	 * setQueryNeedReceiveRefund:查询导出条件 <br/>
	 * @author Administrator
	 * @param dto
	 * @param request
	 * @return
	 * @throws Exception
	 * @since JDK 1.6
	 */
	public NeedReceiveRefundInfoDto setQueryNeedReceiveRefund(NeedReceiveRefundInfoDto dto) throws Exception{
		User currentUser = ShiroUtil.getCurrentUser();
		dto.setOrders(" t.create_time desc ");
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String ysDateStart = dto.getYsDateStart();
		Date ysTimeStart = null;
		if (StringUtils.isNotBlank(ysDateStart)) {
			ysDateStart += " 00:00:00";
			ysTimeStart = sdf.parse(ysDateStart);
		}
		String ysDateEnd = dto.getYsDateEnd();
		Date ysTimeEnd = null;
		if (StringUtils.isNotBlank(ysDateEnd)) {
			ysDateEnd += " 23:59:59";
			ysTimeEnd = sdf.parse(ysDateEnd);
		}
		if("1".equals(dto.getDocType())) {
			//待退款 查询经办日期
			dto.setCreateTimeBefore(ysTimeStart);
			dto.setCreateTimeAfter(ysTimeEnd);
		} else {
			//待收款 查询应收日期
			dto.setReceivablesDateBefore(ysTimeStart);
			dto.setReceivablesDateAfter(ysTimeEnd);
		}
		dto.setDelFlag("0"); // 未删除
		dto.setStatus("1"); // 未结清
		dto.setMerchantId(currentUser.getMerchantId());
		dto.setPermissionUserId(currentUser.getId());
		return dto;
	}

	@RequestMapping(value = "findList", method = RequestMethod.POST)
	@ResponseBody
	public AjaxRes findList(NeedReceiveRefundDto dto) {
		AjaxRes ar = getAjaxRes();
		List<NeedReceiveRefundView> array = new ArrayList<NeedReceiveRefundView>();
		try {
			Long relationId = dto.getRelationId();
			String businessType = dto.getBusinessType();
			if(relationId == null){
				ar.setFailMsg(Const.DATA_FAIL);
				return ar;
			}
			if(StringUtils.isBlank(businessType)){
				ar.setFailMsg(Const.DATA_FAIL);
				return ar;
			}
			if (businessType.equals("2")) {
				Response<Signed> signedResponse = signedServiceFacade.findById(relationId);
				if (signedResponse.isSuccess() && null != signedResponse.getEntity()) {
					Signed signed = signedResponse.getEntity();
					if (!signed.getAuditStatus().equals(AuditStatusEnum.SUCCESS.getNo())) {
						// 审核不通过则取扩展信息
						String extraInformation = signed.getExtraInformation();
						if (StringUtils.isNotBlank(extraInformation)) {
							JSONObject object = JSON.parseObject(extraInformation);
							JSONArray paymentDetails = object.getJSONArray("paymentDetails");
							for (int i = 0; i < paymentDetails.size(); i++) {
								JSONObject row = paymentDetails.getJSONObject(i);
								NeedReceiveRefundView nrf = JSON.parseObject(row.toJSONString(),
										NeedReceiveRefundView.class);
								nrf.setReceiveAmount(row.getString("receivedAmount"));
								if (null != row.getString("needReceivedAmount")) {
									nrf.setUnpaidAmount(new BigDecimal(row.getString("needReceivedAmount")));
									nrf.setNeedReceivedAmount(row.getString("needReceivedAmount"));
								}
								array.add(nrf);
							}
							ar.setSucceed(array);
							return ar;
						}

					}
				}
			}
			ResponseList<NeedReceiveRefund> response = needReceiveRefundServiceFacade.findByDto(dto);
			if (response.isSuccess()) {
				if (null == response.getEntity()) {
					response.setEntity(new ArrayList<NeedReceiveRefund>());
				} else {
					for (int i = 0; i < response.getEntity().size(); i++) {
						NeedReceiveRefundView view = conversionNeedReceiveRefundView(response.getEntity().get(i));
						array.add(view);
					}
					// 查询是否有应收款的的面积补差的金额
					NeedReceiveRefundDto areaNeed = new NeedReceiveRefundDto();
					areaNeed.setRelationId(dto.getRelationId());
					areaNeed.setDocType("0");
					areaNeed.setBusinessType("3");
					ResponseList<NeedReceiveRefund> refund = needReceiveRefundServiceFacade.findByDto(areaNeed);
					if (refund.isSuccess()) {
						if (null != refund.getEntity()) {
							for (NeedReceiveRefund needs : refund.getEntity()) {
								NeedReceiveRefundView areaView = conversionNeedReceiveRefundView(needs);
								array.add(areaView);
							}
						}
					}
					ar.setSucceed(array);
				}

			} else {
				ar.setFailMsg(Const.DATA_FAIL);
			}
		} catch (Exception e) {
			logger.error(e.toString(), e);
			ar.setFailMsg(Const.DATA_FAIL);
		}
		return ar;
	}

	public NeedReceiveRefundView conversionNeedReceiveRefundView(NeedReceiveRefund need) {
		NeedReceiveRefundView view = new NeedReceiveRefundView();
		BeanUtil.convert2T(view, need);
		Response<BigDecimal> res = haveReceiveRefundServiceFacade.findHaveAmount(view.getId());
		if (res.isSuccess()) {
			// 未收金额 = 总金额 - 已收金额
			view.setUnpaidAmount(view.getTotalReceivablesAmount().subtract(res.getEntity()));
			view.setReceiveAmount(res.getEntity().toString());
		} else {
			view.setReceiveAmount("0");
		}
		return view;
	}
	
	// 查看
	@RequestMapping(value = "getNeedReceiveRefundInfo", method = RequestMethod.POST)
	@ResponseBody
	public ExtResultVo getNeedReceiveRefundInfo(Long id) {
		ExtResultVo vo = new ExtResultVo();
		vo.setSuccess(true);
		vo.setData(new JSONObject().toJSONString());
		Response<NeedReceiveRefund> response = needReceiveRefundServiceFacade.findById(id);
		if (response.isSuccess()) {
			NeedReceiveRefund nrr=response.getEntity();
			String nrrStr = JSON.toJSONString(nrr);
			JSONObject data = JSONObject.parseObject(nrrStr);
			Response<BigDecimal> res = haveReceiveRefundServiceFacade.findHaveAmount(nrr.getId());
			if(res.isSuccess()){
				data.put("haveReceivedTotal", res.getEntity());
			}else{
				data.put("haveReceivedTotal","");
			}
			if(null!=nrr.getReceivablesDate()){
				Date delayStartDay=DateUtils.addDay(nrr.getReceivablesDate(), 1);
				data.put("delayStartDay", DateUtils.DateToString(delayStartDay, DateStyle.YYYY_MM_DD));
				data.put("receivablesDate", DateUtils.DateToString(nrr.getReceivablesDate(), DateStyle.YYYY_MM_DD));
			}else{
				data.put("delayStartDay", "");
			}
			
			//已延期天数
			BusinessAbnormaDto queryDto = new BusinessAbnormaDto();
			queryDto.setBusinessId(id);
			queryDto.setBusinessType(BusinessAbnormaEnum.BusinessAbnorma_12.getNo());
			queryDto.setAuditStatus(AuditStatusEnum.SUCCESS.getNo());
			queryDto.setOrders(" t.id asc ");
			ResponseList<BusinessAbnorma> responseList = businessAbnormaServiceFacade.findByDto(queryDto);
			if(responseList.isSuccess() && null!=responseList.getEntity() && responseList.getEntity().size()>0){
				BusinessAbnorma first=responseList.getEntity().get(0);
				Long delayDayCount=DateUtils.getDaysSub(first.getConversionSignDate(), nrr.getReceivablesDate());
				data.put("delayDayCount", delayDayCount);
			}else{
				data.put("delayDayCount", "0");
			}
			
			
			vo.setData(data.toJSONString());
		}
		return vo;
	}
}
